<?php

namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
    public function index()
    {
        $where = [];
        if (input('?id')) {
            $where[] = ['cateid', '=', input('id')];
        }
        $catesInfo = model('Cate')->order('id asc')->select();
        $articlesInfo = model('Article')->where($where)->order('id asc')->paginate(5, false, ['query' => $where]);
        $viewData = [
            'catesInfo' => $catesInfo,
            'articlesInfo' => $articlesInfo
        ];
        $this->assign($viewData);
        return view();
    }

    public function login()
    {
        if (request()->isAjax()) {
            $data = input('post.');
            $result = model('User')->login($data);
            if ($result == 1) {
                $this->success('登录成功！', 'index/index/index');
            }else {
                $this->error($result);
            }
        }
        if (session('?username')) {
            $this->redirect('index/index/index');
        }
        $catesInfo = model('Cate')->order('id asc')->select();
        $viewData = [
            'catesInfo' => $catesInfo
        ];
        $this->assign($viewData);
        return view();
    }

    public function register()
    {
        if (request()->isAjax()) {
            $data = input('post.');
            $result = model('User')->register($data);
            if ($result == 1) {
                $this->success('注册成功！', 'index/index/login');
            }else {
                $this->error($result);
            }
        }
        $catesInfo = model('Cate')->order('id asc')->select();
        $viewData = [
            'catesInfo' => $catesInfo
        ];
        $this->assign($viewData);
        return view();
    }

    public function loginout()
    {
        session(null);
        if (session('?username')) {
            $this->error('退出失败！');
        }else {
            $this->success('退出成功！', 'index/index/index');
        }
    }

    public function article()
    {
        $id = input('id');
        $articleInfo = model('Article')->where('id', $id)->find();
        $catesInfo = model('Cate')->order('id asc')->select();
        $viewData = [
            'articleInfo' => $articleInfo,
            'catesInfo' => $catesInfo
        ];
        $this->assign($viewData);
        return view();
    }
}
